package com.gopay.bis.cmbc.expay.operation;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.ResourceBundle;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;

import com.gopay.bis.cmbc.expay.integrate.SocketAsyncLongOutputAdapter;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import com.gopay.sms.common.domain.ResponseVO;

/**
 * 民生代扣socket监控报警类
 * 
 * @CmbcWarnSMS.java
 * @author zhengxue
 * @2016-12-28 下午1:41:20 www.gopay.com.cn Inc.All rights reserved.
 */
public class CmbcWarnSMS implements InitializingBean {
    private static Log logger = LogFactory.getLog(CmbcWarnSMS.class);
    private SocketAsyncLongOutputAdapter socketAdapter;
    private static ResourceBundle rb = ResourceBundle.getBundle("properties/bis-cmbc");
    private static final AtomicInteger WARN_COUNT = new AtomicInteger(0);

    private static ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    @Override
    public void afterPropertiesSet() throws Exception {
        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                /*String socketMsg = socketAdapter.getSocketMsg();
                logger.info("民生代扣socket监控::::::：" + socketMsg);
                if (!socketAdapter.isConnectSocket()) {
                    logger.info("民生代扣socket连接断开,发送报警短信");
                    if ("on".equals(rb.getString("switchConfig"))) {
                        sendSms(socketMsg);
                    } else {
                        logger.info("民生代扣socket" + socketMsg + "连接断开,报警短信已关闭");
                    }
                }*/
            }
        }, 1, 60, TimeUnit.SECONDS);
    }

    private static void sendSms(String socketMsg) {
        try {
            // 获取电话号
            String mobile = rb.getString("mobile");

            if (WARN_COUNT.get() >= 3) {
                // 报警短信次数超限
                logger.info("socket报警短信超过三次");
                return;
            }

            RequestVO req = new RequestVO();
            req.setAppId(SMSAppId._90000.value);
            req.setMobile(mobile);// 电话号码(多个以逗号分隔)
            req.setContent("cmbc代扣接口socket: " + socketMsg + "已关闭 IP: " + getLocalIp());
            ResponseVO resp = GopaySMSHttpClient.getInstance().createVerificationCode(req);
            if (resp != null) {
                if ("100".equals(resp.getStatusCode())) {
                    logger.info("短信发送成功");
                    WARN_COUNT.incrementAndGet();
                    logger.info("短信提醒次数加1=" + WARN_COUNT.get());
                } else {
                    logger.info("短信发送失败，原因：" + resp.getMessage());
                }
            }
        } catch (Exception e) {
            logger.error("senSMS error: ", e);
        }
    }

    // 获取IP地址
    public static String getLocalIp() throws Exception {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            // System.out.println(netInterface.getName());
            Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address) {
                    logger.info("本机的IP = " + ip.toString());
                    return ip.toString();
                }
            }
        }
        return null;
    }

    public void setSocketAdapter(SocketAsyncLongOutputAdapter socketAdapter) {
        this.socketAdapter = socketAdapter;
    }

}
